package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.spcyService.SpcyQyInfoService;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.MyExcelUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyQyJbxx;
import com.yuncheng.spcyApi.service.ISpcyQyJbxxService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-企业基本信息
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-企业基本信息接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyQyJbxx")
public class SpcyQyJbxxController extends BaseController<SpcyQyJbxx, ISpcyQyJbxxService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyQyJbxxController.class);

    @Resource
    private ISpcyQyJbxxService spcyQyJbxxService;

    @Resource
    private SpcyQyInfoService spcyQyInfoService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Log(title = "企业基本信息-分页列表查询")
    @ApiOperation(value = "企业基本信息-分页列表查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(SpcyQyJbxx spcyQyJbxx,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyQyJbxx> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyQyJbxx> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFtyshxydm()),SpcyQyJbxx::getFtyshxydm,spcyQyJbxx.getFtyshxydm());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyfddbrfzr()),SpcyQyJbxx::getFqyfddbrfzr,spcyQyJbxx.getFqyfddbrfzr());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqylxr()),SpcyQyJbxx::getFqylxr,spcyQyJbxx.getFqylxr());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqymc()),SpcyQyJbxx::getFqymc,spcyQyJbxx.getFqymc());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyzszcdz()),SpcyQyJbxx::getFqyzszcdz,spcyQyJbxx.getFqyzszcdz());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFszdq()),SpcyQyJbxx::getFszdq,spcyQyJbxx.getFszdq());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxxdz()),SpcyQyJbxx::getFxxdz,spcyQyJbxx.getFxxdz());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqyxkzh()),SpcyQyJbxx::getFqyxkzh,spcyQyJbxx.getFqyxkzh());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxzjg()),SpcyQyJbxx::getFxzjg,spcyQyJbxx.getFxzjg());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqylx()),SpcyQyJbxx::getFqylx,spcyQyJbxx.getFqylx());
        wrapper.orderByDesc(SpcyQyJbxx::getCreateTime);
        IPage<SpcyQyJbxx> qyPageList = spcyQyJbxxService.page(page, wrapper);
        return HttpResult.ok(qyPageList);
    }

    /**
     * 分页-查询所有企业信息
     */
    @Log(title = "查询所有企业信息")
    @ApiOperation(value = "查询所有企业信息")
    @GetMapping(value = "/queryAllQyPageList")
    public HttpResult<?> queryAllQyPageList(SpcyQyJbxx spcyQyJbxx,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        Page<SpcyQyJbxx> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyQyJbxx> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFtyshxydm()),SpcyQyJbxx::getFtyshxydm,spcyQyJbxx.getFtyshxydm());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyfddbrfzr()),SpcyQyJbxx::getFqyfddbrfzr,spcyQyJbxx.getFqyfddbrfzr());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqylxr()),SpcyQyJbxx::getFqylxr,spcyQyJbxx.getFqylxr());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqymc()),SpcyQyJbxx::getFqymc,spcyQyJbxx.getFqymc());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyzszcdz()),SpcyQyJbxx::getFqyzszcdz,spcyQyJbxx.getFqyzszcdz());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFszdq()),SpcyQyJbxx::getFszdq,spcyQyJbxx.getFszdq());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxxdz()),SpcyQyJbxx::getFxxdz,spcyQyJbxx.getFxxdz());
        wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqyxkzh()),SpcyQyJbxx::getFqyxkzh,spcyQyJbxx.getFqyxkzh());
        wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxzjg()),SpcyQyJbxx::getFxzjg,spcyQyJbxx.getFxzjg());
        IPage<SpcyQyJbxx> qyPageList = spcyQyJbxxService.page(page, wrapper);

        return HttpResult.ok(qyPageList);
    }

    @Log(title = "企业基本信息-添加")
    @ApiOperation(value = "企业基本信息-添加")
    @PostMapping(value = "/addQyxx")
    public HttpResult<?> addQyxx(@RequestBody SpcyQyJbxx spcyQyJbxx) {

        if (StringUtils.isBlank(spcyQyJbxx.getFtyshxydm())){
            return HttpResult.error("统一社会信用代码不能为空");
        }

        if (StringUtils.isBlank(spcyQyJbxx.getFqymc())){
            return HttpResult.error("企业名称不能为空");
        }

        List<SpcyQyJbxx> xydmList = spcyQyJbxxService.list(new LambdaQueryWrapper<SpcyQyJbxx>()
                .eq(SpcyQyJbxx::getFtyshxydm, spcyQyJbxx.getFtyshxydm()));
        // 判断企业是否存在
        if (CollectionUtils.isEmpty(xydmList)) {

            spcyQyJbxx.setFwfcs(0);
            spcyQyJbxxService.save(spcyQyJbxx);

            String operContent = "新增信息：";

            // 将map里面的属性和值转String
            Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyQyJbxx);
            operContent += LogUtils.MapToStringMethod(beanMap);
            spcyLogService.addLogs(LogConstant.LOGS_QY_JBXX, operContent, spcyQyJbxx.getId(), LogConstant.LOGS_QY_JBXX, SpcyConstant.LOGS_SYS_TYPE_XZ);

            HttpResult result = new HttpResult(true);
            result.setResult(spcyQyJbxx);
            result.setMessage("添加成功");
            return result;
        }else {
            return HttpResult.error("社会信用代码相关的企业【"+spcyQyJbxx.getFqymc()+"】已经存在了");
        }
    }

    @Log(title = "企业基本信息-编辑")
    @ApiOperation(value = "企业基本信息-编辑")
    @PutMapping(value = "/editQyxx")
    public HttpResult<?> editQyxx(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        return spcyQyInfoService.editQyxx(buffer);
    }


    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "企业基本信息-批量删除")
    @ApiOperation(value = "企业基本信息-批量删除")
    @DeleteMapping(value = "/deleteBatchQyxx")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyQyJbxx> spcyQyJbxxes = spcyQyJbxxService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyQyJbxxes)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyQyJbxx qyJbxx : spcyQyJbxxes){
            String id = qyJbxx.getId();
            spcyQyJbxxService.removeById(id);
            spcyQyInfoService.deleteQyInfoXX(id); // 删除企业相关信息

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(qyJbxx);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_QY_JBXX,operContent,id,LogConstant.LOGS_QY_JBXX,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "企业基本信息-通过id查询")
    @ApiOperation(value = "企业基本信息-通过id查询")
    @GetMapping(value = "/queryQyxxById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyQyJbxx spcyQyJbxx = spcyQyJbxxService.getById(id);
        return HttpResult.ok(spcyQyJbxx);
    }

    /**
     * 导入企业基本信息数据-表格excel
     */
    @Log(title = "导入企业基本信息数据-表格excel")
    @ApiOperation(value = "导入企业基本信息数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true)
    })
    @PostMapping(value = "impQyJbxxData")
    public HttpResult<?> impQyJbxxData(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_QY_JBXX_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入企业基本信息数据出错-{}",e.getMessage());
        }
        StringBuffer msg = new StringBuffer();
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            int index = 0;
            for (Map map : mapsList) {
                index++;
                SpcyQyJbxx qyJbxx = new SpcyQyJbxx();
                BeanUtil.copyProperties(map,qyJbxx);
                String qyid = GetUuIdUtils.ReplaceUuId();
                qyJbxx.setId(qyid);

                if (qyJbxx != null && StringUtils.isNotBlank(qyJbxx.getFtyshxydm())) {
                    List<SpcyQyJbxx> xydmList = spcyQyJbxxService.list(new LambdaQueryWrapper<SpcyQyJbxx>()
                            .eq(SpcyQyJbxx::getFtyshxydm, qyJbxx.getFtyshxydm()));
                    // 判断企业是否存在
                    if (CollectionUtils.isEmpty(xydmList)) {
                        spcyQyJbxxService.save(qyJbxx);

                        String operContent = "新增导入信息：";

                        // 将map里面的属性和值转String
                        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(qyJbxx);
                        operContent += LogUtils.MapToStringMethod(beanMap);
                        spcyLogService.addLogs(LogConstant.LOGS_QY_JBXX, operContent, qyid, LogConstant.LOGS_QY_JBXX, SpcyConstant.LOGS_SYS_TYPE_XZ);
                    }else {
                        log.info("导入企业名称为{},统一社会信用代码为{}的企业已经存在。",qyJbxx.getFqymc(),qyJbxx.getFtyshxydm());
                        msg.append("第").append(index).append("条");
                        msg.append("导入企业名称为[").append(qyJbxx.getFqymc());
                        msg.append("]，统一社会信用代码为[").append(qyJbxx.getFtyshxydm()).append("]的企业已经存在。");
                    }
                }else {
                    String qymc = "";
                    if (qyJbxx != null) {
                        qymc = qyJbxx.getFqymc();
                    }
                    log.info("导入企业名称为{}的企业社会信用代码为空,导入失败。", qymc);
                    msg.append("第").append(index).append("条，导入企业名称为[").append(qymc).append("]社会信用代码为空");
                }
            }
        }else {
            msg.append("导入模板数据不能为空");
        }
        fileUpload.delete();
        if (StringUtils.isNotBlank(msg)){
            return HttpResult.ok(msg);
        }
        return HttpResult.ok("导入成功");
    }

    /**
     * 下载企业基本信息-导入模板
     * @param response
     */
    @Log(title = "下载企业基本信息-导入模板")
    @ApiOperation(value = "下载企业基本信息-导入模板")
    @GetMapping("/downQyJbxxTemplate")
    public void downQyJbxxTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("qyJbxxImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_QY_JBXX_XML, out);
        } catch (Exception e) {
            log.error("下载企业基本信息模板错误-{}",e.getMessage());
        }
    }

    /**
     * 导出企业基本信息数据-表格excel
     */
    @Log(title = "导出企业基本信息数据-表格excel")
    @ApiOperation(value = "导出企业基本信息数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "企业基本信息id字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportQyJbxxData")
    public void exportQyJbxxData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                   SpcyQyJbxx spcyQyJbxx,
                                   HttpServletResponse response){
        try {
            String name = "exportQyJbxxData";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyQyJbxx> qyJbxxList = spcyQyJbxxService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(qyJbxxList)){
                    for (SpcyQyJbxx e : qyJbxxList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyQyJbxx> wrapper = new LambdaQueryWrapper<>();
                wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFtyshxydm()),SpcyQyJbxx::getFtyshxydm,spcyQyJbxx.getFtyshxydm());
                wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyfddbrfzr()),SpcyQyJbxx::getFqyfddbrfzr,spcyQyJbxx.getFqyfddbrfzr());
                wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqylxr()),SpcyQyJbxx::getFqylxr,spcyQyJbxx.getFqylxr());
                wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqymc()),SpcyQyJbxx::getFqymc,spcyQyJbxx.getFqymc());
                wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFqyzszcdz()),SpcyQyJbxx::getFqyzszcdz,spcyQyJbxx.getFqyzszcdz());
                wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFszdq()),SpcyQyJbxx::getFszdq,spcyQyJbxx.getFszdq());
                wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxxdz()),SpcyQyJbxx::getFxxdz,spcyQyJbxx.getFxxdz());
                wrapper.like(StringUtils.isNotEmpty(spcyQyJbxx.getFqyxkzh()),SpcyQyJbxx::getFqyxkzh,spcyQyJbxx.getFqyxkzh());
                wrapper.like(StringUtils.isNotBlank(spcyQyJbxx.getFxzjg()),SpcyQyJbxx::getFxzjg,spcyQyJbxx.getFxzjg());
                List<SpcyQyJbxx> qyJbxxList = spcyQyJbxxService.list(wrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(qyJbxxList)){
                    for (SpcyQyJbxx e : qyJbxxList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_QY_JBXX_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出企业基本信息数据出错-{}",e.getMessage());
        }
    }

}
